
package com.epam.android.training.level1.widget;

import com.epam.android.training.level1.R;
import com.epam.android.training.level1.activity.IntentActions;
import com.epam.android.training.level1.db.dao.PollDao;
import com.epam.android.training.level1.db.dao.RssDao;
import com.epam.android.training.level1.db.dao.impl.PollDaoImpl;
import com.epam.android.training.level1.db.dao.impl.RssDaoImpl;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

/**
 * @author Anton Novikau
 */
public class AppWidget extends AppWidgetProvider implements IntentActions {
  RssDao rssDao;

  PollDao pollDao;

  @Override
  public void onReceive(Context context, Intent intent) {
    rssDao = new RssDaoImpl(context);
    pollDao = new PollDaoImpl(context);
    String action = intent.getAction();
    if (ACTION_RENEW_WIDGET.equals(action)) {
      RemoteViews views = renewWidget(context);
      ComponentName provider = new ComponentName(context, AppWidget.class);
      AppWidgetManager.getInstance(context).updateAppWidget(provider, views);
    } else {
      super.onReceive(context, intent);
    }
  }

  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for (int widgetId : appWidgetIds) {
      RemoteViews views = renewWidget(context);

      Intent onFeedClick = new Intent(ACTION_NEWS);
      PendingIntent onFeedClickPendingIntent = PendingIntent.getActivity(context, 0, onFeedClick,
          PendingIntent.FLAG_UPDATE_CURRENT);
      views.setOnClickPendingIntent(R.id.widget_feed_row, onFeedClickPendingIntent);

      Intent onPollClick = new Intent(ACTION_TESTS);
      PendingIntent onPollClickPendingIntent = PendingIntent.getActivity(context, 0, onPollClick,
          PendingIntent.FLAG_UPDATE_CURRENT);
      views.setOnClickPendingIntent(R.id.widget_poll_row, onPollClickPendingIntent);

      appWidgetManager.updateAppWidget(widgetId, views);
    }
  }

  private RemoteViews renewWidget(Context context) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget);

    views.setTextViewText(R.id.last_feed_item, rssDao.getLatestNewsTitle());
    views.setTextViewText(R.id.last_poll, pollDao.getNewestPollTitle());
    return views;
  }
}
